package eproject.mm.com.projectsupervision.fragment;


import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PersistableBundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.LinearInterpolator;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.xiasuhuei321.loadingdialog.view.LoadingDialog;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.ColorTransitionPagerTitleView;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import cn.carbs.android.segmentcontrolview.library.SegmentControlView;
import eproject.mm.com.projectsupervision.MainActivity;
import eproject.mm.com.projectsupervision.PrjApplication;
import eproject.mm.com.projectsupervision.R;
import eproject.mm.com.projectsupervision.activity.CardActivity;
import eproject.mm.com.projectsupervision.activity.ProblemActivity;
import eproject.mm.com.projectsupervision.activity.ProblemListActivity;
import eproject.mm.com.projectsupervision.activity.ProjectActivity;
import eproject.mm.com.projectsupervision.activity.QuantityActivity;
import eproject.mm.com.projectsupervision.activity.ReportActivity;
import eproject.mm.com.projectsupervision.adapter.BaseFragmentPagerAdapter;
import eproject.mm.com.projectsupervision.adapter.MainPagerAdapter;
import eproject.mm.com.projectsupervision.adapter.ProjectPagerAdapter;
import eproject.mm.com.projectsupervision.adapter.RecyclerViewAdapter;
import eproject.mm.com.projectsupervision.service.MyJobService;
import eproject.mm.com.projectsupervision.util.HttpUtil;
import eproject.mm.com.projectsupervision.util.LocationUtil;
import eproject.mm.com.projectsupervision.util.TimeUtil;
import eproject.mm.com.projectsupervision.widget.IconFontTextview;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import android.speech.tts.TextToSpeech;

import org.json.JSONObject;

import static android.content.Context.JOB_SCHEDULER_SERVICE;

/**
 * A simple {@link Fragment} subclass.
 */
public class MainFragment extends Fragment implements View.OnClickListener{
    String TAG = "MainFragment";
    TextToSpeech tts;

    RelativeLayout rl_home_planReportSubmit,rl_home_planReportSubmit2,rl_home_problemSubmit;
    ViewPager viewPager;
    private BaseFragmentPagerAdapter baseFragmentPagerAdapter;
    MagicIndicator magicIndicator;
    List<String> mTitleDataList;

    private ArrayList<View> vList;
    private MainPagerAdapter mainAdapter;
    private SegmentControlView mainInfoTab;
    private RecyclerView rv_info;

    private AlphaAnimation mShowAnim, mHiddenAmin;

    LinearLayout ll_topArea;
    private static int THRESHOLD_OFFSET = 10;

    private List<LazyFragment> fragmentList;

    //
    LinearLayout ll_problem_all,ll_rate_all;
    IconFontTextview iftv_topShow,iftv_topHide;

    TextView tv_summaryRate, tv_plan_doing, tv_plan_done, tv_plan_over;
    TextView tv_problem_count, tv_problem_doing, tv_problem_done, tv_problem_over;

    IconFontTextview iftv_card;
    TextView tv_workStatus;
    SharedPreferences userSettings;
    String workDate, workStatus;

    private String Process_Name = "eproject.mm.com.projectsupervision:localService";

    private OkHttpClient client;

    public MainFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_main, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        userSettings = getActivity().getApplication().getSharedPreferences("setting", Context.MODE_MULTI_PROCESS);
        workDate = userSettings.getString("workdate","");
        workStatus = userSettings.getString("workstatus","0");

        //控件显示的动画
        mShowAnim = new AlphaAnimation(0.0f, 1.0f);
        mShowAnim.setDuration(300);

        //控件隐藏的动画
        mHiddenAmin = new AlphaAnimation(1.0f, 0.0f);
        mHiddenAmin.setDuration(300);

        ll_problem_all = (LinearLayout) getView().findViewById(R.id.ll_problem_all);
        ll_rate_all = (LinearLayout) getView().findViewById(R.id.ll_rate_all);

        ll_topArea = (LinearLayout) getView().findViewById(R.id.ll_topArea);
        rl_home_planReportSubmit = (RelativeLayout) getView().findViewById(R.id.rl_home_planReportSubmit);
        rl_home_planReportSubmit2 = (RelativeLayout) getView().findViewById(R.id.rl_home_planReportSubmit2);

        rl_home_problemSubmit = (RelativeLayout) getView().findViewById(R.id.rl_home_problemSubmit);

        iftv_topShow = (IconFontTextview) getView().findViewById(R.id.iftv_topShow);
        iftv_topHide = (IconFontTextview) getView().findViewById(R.id.iftv_topHide);

        viewPager = (ViewPager) getView().findViewById(R.id.vp_info);
        viewPager.setOffscreenPageLimit(3);


        tv_summaryRate = (TextView) getView().findViewById(R.id.tv_summaryRate);
        tv_plan_doing = (TextView) getView().findViewById(R.id.tv_plan_doing);
        tv_plan_done = (TextView) getView().findViewById(R.id.tv_plan_done);
        tv_plan_over = (TextView) getView().findViewById(R.id.tv_plan_over);

        tv_problem_count = (TextView) getView().findViewById(R.id.tv_problem_count);
        tv_problem_doing = (TextView) getView().findViewById(R.id.tv_problem_doing);
        tv_problem_done = (TextView) getView().findViewById(R.id.tv_problem_done);
        tv_problem_over = (TextView) getView().findViewById(R.id.tv_problem_over);

        loadData();

        fragmentList = new ArrayList<LazyFragment>();
        LazyFragment lazyFragment01 = new BaseFragment();
        LazyFragment lazyFragment02 = new BaseFragment();
        LazyFragment lazyFragment03 = new BaseFragment();
        LazyFragment lazyFragment04 = new BaseFragment();

        Bundle bundle1 = new Bundle();
        bundle1.putString("type", "0");
        lazyFragment01.setArguments(bundle1);

        Bundle bundle2 = new Bundle();
        bundle2.putString("type", "1");
        lazyFragment02.setArguments(bundle2);

        Bundle bundle3 = new Bundle();
        bundle3.putString("type", "2");
        lazyFragment03.setArguments(bundle3);

        Bundle bundle4 = new Bundle();
        bundle4.putString("type", "3");
        lazyFragment04.setArguments(bundle4);

        fragmentList.add(lazyFragment01);
        fragmentList.add(lazyFragment02);
        fragmentList.add(lazyFragment03);
        fragmentList.add(lazyFragment04);

        FragmentManager fm = getActivity().getSupportFragmentManager();
        baseFragmentPagerAdapter = new BaseFragmentPagerAdapter(fm, fragmentList);
        viewPager.setAdapter(baseFragmentPagerAdapter);
        viewPager.setCurrentItem(0);

        mainInfoTab = (SegmentControlView)getActivity().findViewById(R.id.mainInfoTab);
        mainInfoTab.setViewPager(viewPager);

//        rv_info = (RecyclerView)vList.get(0).findViewById(R.id.rv_info);
//        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
//        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
//        rv_info.setLayoutManager(layoutManager);
//
//        String[] title = {"Blog : http://blog.csdn.net/Leejizhou.",
//                "A good laugh and a long sleep are the best cures in the doctor's book.",
//                "all or nothing, now or never "
//                ,"","","","","",""
//        };
//        rv_info.setAdapter(new RecyclerViewAdapter(getActivity(), title));

        iftv_card = (IconFontTextview)getView().findViewById(R.id.iftv_card);
        tv_workStatus = (TextView)getView().findViewById(R.id.tv_workstatus);

        initEvent();

        if(workDate.equals(TimeUtil.getCurrDate())){
            if(workStatus.equals("1")){
                tv_workStatus.setText("工作中");
                tv_workStatus.setVisibility(View.VISIBLE);
                iftv_card.setTextColor(getResources().getColor(R.color.workOn));

                if(!PrjApplication.getInstance().isServiceStarted()){
                    PrjApplication.getInstance().StartLocalService(0);
                }
                Intent intent = new Intent(PrjApplication.getInstance().ServiceStartAction);
                intent.putExtra("flag",0);
                getActivity().sendBroadcast(intent);

                //启动定时任务
                addJobScheduler();
            }else{
                tv_workStatus.setVisibility(View.GONE);
                iftv_card.setTextColor(getResources().getColor(R.color.workOff));

                //取消定时任务
                removeJobScheduler();
            }
        }else{
            tv_workStatus.setVisibility(View.GONE);
            iftv_card.setTextColor(getResources().getColor(R.color.workOff));

            //取消定时任务
            removeJobScheduler();
        }

        client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .build();
    }
    private void initEvent(){
        mainInfoTab.setOnSegmentChangedListener(new SegmentControlView.OnSegmentChangedListener() {
            @Override
            public void onSegmentChanged(int newSelectedIndex) {
                viewPager.setCurrentItem(newSelectedIndex, false);
            }
        });
        rl_home_planReportSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), ReportActivity.class);
                Bundle bundle=new Bundle();
                bundle.putString("id", "");
                intent.putExtras(bundle);
                startActivityForResult(intent,0);
            }
        });
        rl_home_planReportSubmit2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), QuantityActivity.class);
                Bundle bundle=new Bundle();
                bundle.putString("id", "");
                intent.putExtras(bundle);
                startActivityForResult(intent,0);
            }
        });

        rl_home_problemSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), ProblemActivity.class);
                Bundle bundle=new Bundle();
                bundle.putString("id", "");
                intent.putExtras(bundle);
                startActivityForResult(intent,0);
            }
        });

        iftv_topShow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                iftv_topShow.setVisibility(View.GONE);
                iftv_topHide.setVisibility(View.VISIBLE);
                animationShow();
            }
        });
        iftv_topHide.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                iftv_topShow.setVisibility(View.VISIBLE);
                iftv_topHide.setVisibility(View.GONE);
                animationHide();
            }
        });

        ll_problem_all.setOnClickListener(this);
        tv_problem_count.setOnClickListener(this);

        ll_rate_all.setOnClickListener(this);
        tv_summaryRate.setOnClickListener(this);

        iftv_card.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), CardActivity.class);
                getActivity().startActivityForResult(intent,0);
                if(1==1)return;
                workDate = userSettings.getString("workdate","");
                workStatus = userSettings.getString("workstatus","0");

                final SharedPreferences.Editor editor = userSettings.edit();
                if(workDate.equals(TimeUtil.getCurrDate())){
                    if(workStatus.equals("1")){
                        Location location = LocationUtil.getLocation(getActivity());
                        if(location==null){
                            Toast.makeText(getActivity(),"获取定位信息失败,请开启GPS定位",Toast.LENGTH_SHORT).show();
                        }else{
                            //Toast.makeText(getActivity(),"经度：" + location.getLongitude() + ", 纬度："
                            //        + location.getLatitude(),Toast.LENGTH_SHORT).show();
                            final LoadingDialog loadingDialog = new LoadingDialog(getActivity());
                            loadingDialog.setLoadingText("加载中...")//设置loading时显示的文字
                                    .show();
                            try {
                                //SharedPreferences sysSetting = getActivity().getApplicationContext().getSharedPreferences("setting", 0);
                                int stepCount = userSettings.getInt("stepCount",0);
                                okhttp3.FormBody.Builder builder = new okhttp3.FormBody.Builder();
                                builder.add("type","1");
                                builder.add("x",location.getLongitude()+"");
                                builder.add("y",location.getLatitude()+"");
                                builder.add("stepcount",stepCount+"");
                                RequestBody requestBody = builder.build();
                                Request.Builder okbuilder = new Request.Builder();
                                okbuilder.addHeader("authenticationToken", PrjApplication.getInstance().getAuthenticationToken());
                                Request requestPostCard = okbuilder
                                        .url("http://"+ PrjApplication.getInstance().getServerIp() +":"+PrjApplication.getInstance().getServerPort()+"/"+PrjApplication.getInstance().getPreFixPath()+"/saveCardRecord")
                                        .post(requestBody)
                                        .build();
                                client.newCall(requestPostCard).enqueue(new Callback() {
                                    @Override
                                    public void onFailure(Call call, IOException e) {
                                        loadingDialog.close();
                                    }

                                    @Override
                                    public void onResponse(Call call, final Response response) throws IOException {
                                        getActivity().runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                loadingDialog.close();

                                                Intent intent = new Intent(PrjApplication.getInstance().ServiceStopAction);
                                                getActivity().sendBroadcast(intent);

                                                //PrjApplication.getInstance().StopLocalService();

                                                tv_workStatus.setText("");
                                                tv_workStatus.setVisibility(View.GONE);
                                                editor.putString("workstatus", "0");
                                                iftv_card.setTextColor(getResources().getColor(R.color.workOff));

                                                editor.commit();

                                                //取消定时任务
                                                removeJobScheduler();
                                                //停止工作
                                            }
                                        });
                                    }
                                });
                            }catch (Exception e){
                                loadingDialog.close();
                            }
                        }


                    }else {
                        Location location = LocationUtil.getLocation(getActivity());
                        if(location==null){
                            Toast.makeText(getActivity(),"获取定位信息失败,请开启GPS定位",Toast.LENGTH_SHORT).show();
                        }else{
                            //Toast.makeText(getActivity(),"经度：" + location.getLongitude() + ", 纬度："
                            //        + location.getLatitude(),Toast.LENGTH_SHORT).show();
                            final LoadingDialog loadingDialog = new LoadingDialog(getActivity());
                            loadingDialog.setLoadingText("加载中...")//设置loading时显示的文字
                                    .show();
                            try {
                                okhttp3.FormBody.Builder builder = new okhttp3.FormBody.Builder();
                                builder.add("type","0");
                                builder.add("x",location.getLongitude()+"");
                                builder.add("y",location.getLatitude()+"");
                                RequestBody requestBody = builder.build();
                                Request.Builder okbuilder = new Request.Builder();
                                okbuilder.addHeader("authenticationToken", PrjApplication.getInstance().getAuthenticationToken());
                                Request requestPostCard = okbuilder
                                        .url("http://"+ PrjApplication.getInstance().getServerIp() +":"+PrjApplication.getInstance().getServerPort()+"/"+PrjApplication.getInstance().getPreFixPath()+"/saveCardRecord")
                                        .post(requestBody)
                                        .build();
                                client.newCall(requestPostCard).enqueue(new Callback() {
                                    @Override
                                    public void onFailure(Call call, IOException e) {
                                        loadingDialog.close();
                                    }

                                    @Override
                                    public void onResponse(Call call, final Response response) throws IOException {
                                        getActivity().runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                loadingDialog.close();

                                                if(editor.putInt("stepCount", 0).commit()) {
                                                    Intent intent = new Intent(PrjApplication.getInstance().ServiceStartAction);
                                                    intent.putExtra("flag",1);
                                                    getActivity().sendBroadcast(intent);

                                                    editor.putString("workstatus", "1");
                                                    iftv_card.setTextColor(getResources().getColor(R.color.workOn));
                                                    tv_workStatus.setText("工作中");

                                                    tv_workStatus.setVisibility(View.VISIBLE);
                                                    editor.commit();

                                                    //取消定时任务
                                                    addJobScheduler();
                                                }
                                            }
                                        });
                                    }
                                });
                            }catch (Exception e){
                                loadingDialog.close();
                            }
                        }

                    }
                }else{
                    Location location = LocationUtil.getLocation(getActivity());
                    if(location==null){
                        Toast.makeText(getActivity(),"获取定位信息失败,请开启GPS定位",Toast.LENGTH_SHORT).show();
                    }else{
                        //Toast.makeText(getActivity(),"经度：" + location.getLongitude() + ", 纬度："
                        //        + location.getLatitude(),Toast.LENGTH_SHORT).show();
                        final LoadingDialog loadingDialog = new LoadingDialog(getActivity());
                        loadingDialog.setLoadingText("加载中...")//设置loading时显示的文字
                                .show();
                        try {
                            okhttp3.FormBody.Builder builder = new okhttp3.FormBody.Builder();
                            builder.add("type","0");
                            builder.add("x",location.getLongitude()+"");
                            builder.add("y",location.getLatitude()+"");
                            RequestBody requestBody = builder.build();
                            Request.Builder okbuilder = new Request.Builder();
                            okbuilder.addHeader("authenticationToken", PrjApplication.getInstance().getAuthenticationToken());
                            Request requestPostCard = okbuilder
                                    .url("http://"+ PrjApplication.getInstance().getServerIp() +":"+PrjApplication.getInstance().getServerPort()+"/"+PrjApplication.getInstance().getPreFixPath()+"/saveCardRecord")
                                    .post(requestBody)
                                    .build();
                            client.newCall(requestPostCard).enqueue(new Callback() {
                                @Override
                                public void onFailure(Call call, IOException e) {
                                    loadingDialog.close();
                                }

                                @Override
                                public void onResponse(Call call, final Response response) throws IOException {
                                    getActivity().runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            loadingDialog.close();

                                            if(editor.putInt("stepCount", 0).commit()) {
                                                Intent intent = new Intent(PrjApplication.getInstance().ServiceStartAction);
                                                intent.putExtra("flag",1);
                                                getActivity().sendBroadcast(intent);
                                                //PrjApplication.getInstance().StartLocalService(1);

                                                //Intent intent = new Intent(PrjApplication.getInstance().RestStepCountAction);
                                                //getContext().sendBroadcast(intent);

                                                editor.putString("workdate", TimeUtil.getCurrDate());
                                                editor.putString("workstatus", "1");
                                                iftv_card.setTextColor(getResources().getColor(R.color.workOn));
                                                tv_workStatus.setText("工作中");
                                                tv_workStatus.setVisibility(View.VISIBLE);
                                                editor.commit();

                                                //取消定时任务
                                                addJobScheduler();
                                            }
                                        }
                                    });
                                }
                            });
                        }catch (Exception e){
                            loadingDialog.close();
                        }
                    }
                }
                //editor.commit();
            }
        });
    }
    void animationShow(){
        ll_topArea.startAnimation(mShowAnim);
        ll_topArea.setVisibility(View.VISIBLE);
//        ll_topArea.animate()
//                .setInterpolator(new AccelerateInterpolator(1))
//                .setDuration(180)
//                .translationY(0);
    }
    void animationHide(){
        ll_topArea.startAnimation(mHiddenAmin);
        ll_topArea.setVisibility(View.GONE);
//        ll_topArea.animate()
//                .translationY(-ll_topArea.getBottom())
//                .setInterpolator(new LinearInterpolator())
//                .setDuration(180);
    }


    private void loadData(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String resultStr = HttpUtil.get("/getSumPercentDoneByCreator");

                    handler.sendMessage(handler.obtainMessage(1, resultStr));
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(getActivity(),e.toString(),Toast.LENGTH_SHORT);
                }
            }
        }).start();
    }

    DecimalFormat df0 = new DecimalFormat("#");
    DecimalFormat df2 = new DecimalFormat("#.00");

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    String str = (String)msg.obj;
                    Gson gson=new Gson();
                    Map resultMap = gson.fromJson(str, Map.class);
                    if (resultMap != null && (boolean) resultMap.get("success")) {
                        Map planMap = (Map)resultMap.get("plan");
                        Map problemMap = (Map)resultMap.get("problem");

                        Double dCount = (Double)problemMap.get("count");
                        Double dDonging = (Double)problemMap.get("donging");
                        Double dDone = (Double)problemMap.get("done");
                        Double dOver = (Double)problemMap.get("over");
                        tv_problem_count.setText(df0.format(dCount));
                        tv_problem_doing.setText(df0.format(dDonging));
                        tv_problem_done.setText(df0.format(dDone));
                        tv_problem_over.setText(df0.format(dOver));

                        Double dPRate = (Double)planMap.get("summaryrate");
                        Double dPDonging = (Double)planMap.get("donging");
                        Double dPDone = (Double)planMap.get("done");
                        Double dPOver = (Double)planMap.get("over");
                        tv_summaryRate.setText(df2.format(dPRate)+"%");
                        tv_plan_doing.setText(df0.format(dPDonging));
                        tv_plan_done.setText(df0.format(dPDone));
                        tv_plan_over.setText(df0.format(dPOver));
                    }
                    break;
                case 2:
                    break;
                default:
                    super.handleMessage(msg);
                    break;
            }
        }
    };

    public void onClick(View v) {
        if(v == ll_problem_all || v == tv_problem_count) {
            Intent intent = new Intent(getActivity(), ProblemListActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("type", "0");
            intent.putExtras(bundle);
            startActivityForResult(intent, 0);
        }else if(v == ll_rate_all || v == tv_summaryRate) {
            Intent intent = new Intent(PrjApplication.getInstance().TabChangeAction);
            getActivity().sendBroadcast(intent);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    public void setWorkStatus(int status){
        if(status==1){//on
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    iftv_card.setTextColor(getResources().getColor(R.color.workOn));
                    tv_workStatus.setText("工作中");
                    tv_workStatus.setVisibility(View.VISIBLE);
                }
            });
        }else if(status==2){//off
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    tv_workStatus.setText("");
                    tv_workStatus.setVisibility(View.GONE);
                    iftv_card.setTextColor(getResources().getColor(R.color.workOff));
                }
            });
        }
    }


    private void addJobScheduler(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            removeJobScheduler();
            try {
                PersistableBundle extBundle = new PersistableBundle();
                extBundle.putString("token",PrjApplication.getInstance().getAuthenticationToken());
                String urlStr = "http://"+ PrjApplication.getInstance().getServerIp() +":"+PrjApplication.getInstance().getServerPort()+"/"+PrjApplication.getInstance().getPreFixPath();
                extBundle.putString("url",urlStr);

                JobScheduler jobScheduler = (JobScheduler) getActivity().getSystemService(JOB_SCHEDULER_SERVICE);
                JobInfo jobInfo = new JobInfo.Builder(1, new ComponentName(getActivity().getPackageName(), MyJobService.class.getName()))
                        .setRequiresCharging(false)
                        .setRequiresDeviceIdle(false)
                        //.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY) //任何有网络的状态
                        .setPersisted(false) //系统重启后保留job
                        //.setPeriodic(1000 * 15) //这里的单位是毫秒,1000 * 60 * 60 * 24代表一天(24小时)
                        .setMinimumLatency(1 * 60 * 1000L)
                        .setOverrideDeadline(1 * 60 * 1000L)
                        .setExtras(extBundle)
                        .build();

                int result = jobScheduler.schedule(jobInfo);
                Log.d(TAG, "result:" + result);
                Toast.makeText(getContext(),"JobScheduler started",Toast.LENGTH_SHORT).show();
            } catch (Exception ex) {
                Log.e(TAG,ex.getMessage());
                Toast.makeText(getContext(),"无法启动JobScheduler",Toast.LENGTH_SHORT).show();
            }
        }else{
            Toast.makeText(getContext(),"无法启动JobScheduler,系统版本过低",Toast.LENGTH_SHORT).show();
        }
    }
    private void removeJobScheduler(){
        JobScheduler tm = (JobScheduler) getActivity().getSystemService(JOB_SCHEDULER_SERVICE);
        tm.cancelAll();
    }
}
